package com.sample.view.components
{
	import com.trg.flex.FlexUtils;
	
	import flash.events.EventDispatcher;
	import flash.xml.XMLNode;
	import flash.xml.XMLNodeType;
	
	[Event(name="select", type="com.sample.view.components.NavEvent")]
	[DefaultProperty("children")]
	public class NavNode extends EventDispatcher
	{
		public var name:String;
		public var label:String;
		public var defaultChild:String;
		
		public function fire():void {
			dispatchEvent(new NavEvent("select", name));
		}
		
		[ArrayElementType("com.sample.view.components.NavNode")]
		public var children:Array;
		
		public function getXML():XMLNode {
			var xml:XMLNode = new XMLNode(XMLNodeType.ELEMENT_NODE, "");
			xml.nodeName = "node";
			xml.attributes = {
				name: name,
				label: label
			};
			if (defaultChild) {
				xml.attributes.defaultChild = defaultChild;
			}
			
			for each (var child:NavNode in children) {
				xml.appendChild(child.getXML());
			}
			return xml;
		}
		
		public function getChildren():Array {
			return children;
		}
		
		public function getDescendants():Array {
			var array:Array = FlexUtils.copyArray(children);
			for each (var child:NavNode in children) {
				for each (var descendant:NavNode in child.getDescendants()) {
					array.push(descendant);
				}
			}
			return array;
		}
	}
}